// src/store/modules/cartModule.ts
// import { CartState, GoodsItem } from '@/types';
import { getCartList, changeCount, delSelect } from '@/api/cart';


export interface GoodsItem {
  id: number;
  goods_id: number;
  goods_num: number;
  isChecked: boolean;
  goods: {
    goods_price_min: number;
  };
}

interface CartState {
  cartList: GoodsItem[];
}

const cartModule = {
  namespaced: true as const,
  state: (): CartState => ({
    cartList: [],
  }),
  getters: {
    cartTotal(state: CartState): number {
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0);
    },
    selCartList(state: CartState): GoodsItem[] {
      return state.cartList.filter(item => item.isChecked);
    },
    selCount(_: any, getters: any): number {
      return getters.selCartList.reduce((sum: number, item: GoodsItem) => sum + item.goods_num, 0);
    },
    selPrice(_: any, getters: any): string {
      const total = getters.selCartList.reduce((sum: number, item: GoodsItem) => {
        return sum + item.goods_num * item.goods.goods_price_min;
      }, 0);
      return total.toFixed(2);
    },
    isAllChecked(state: CartState): boolean {
      return state.cartList.every(item => item.isChecked);
    }
  },
  mutations: {
    setCartList(state: CartState, list: GoodsItem[]) {
      state.cartList = list;
    },
    toggleCheck(state: CartState, goodsId: number) {
      const goods = state.cartList.find(item => item.goods_id === goodsId);
      if (goods) goods.isChecked = !goods.isChecked;
    },
    toggleAllCheck(state: CartState, flag: boolean) {
      state.cartList.forEach(item => item.isChecked = flag);
    },
    changeCount(state: CartState, { goodsId, goodsNum }: { goodsId: number; goodsNum: number }) {
      const goods = state.cartList.find(item => item.goods_id === goodsId);
      if (goods) goods.goods_num = goodsNum;
    }
  },
  actions: {
    async getCartAction({ commit }: { commit: Function }) {
      const { data } = await getCartList();
      data.list.forEach((item: GoodsItem) => item.isChecked = true);
      commit('setCartList', data.list);
    },
    async changeCountAction({ commit }: { commit: Function }, payload: any) {
      commit('changeCount', { goodsId: payload.goodsId, goodsNum: payload.goodsNum });
      await changeCount(payload.goodsId, payload.goodsNum, payload.goodsSkuId);
    },
    async delSelect({ dispatch }: { dispatch: Function }, rootGetters: any) {
      const selected = rootGetters['cart/selCartList'];
      const ids = selected.map((item: any) => item.id);
      await delSelect(ids);
      uni.showToast({ title: "删除成功" });
      await dispatch('getCartAction');
    }
  }
};

export default cartModule;